<template>
  <div class="app-container">
    <div class="block">
      <el-button
        size="mini"
        type="success"
        v-permission="['/business/food/edit']"
        @click="addFood(selectTable)"
        >添加食品
      </el-button>
      <el-button size="mini" type="info" @click="viewFood(selectTable)">查看食品 </el-button>

      <el-button size="mini" type="primary" @click="updateShop">提交修改 </el-button>
    </div>
    <br />

    <el-form :model="selectTable">
      <el-form-item label="审核状态" label-width="120px">
        <el-input v-model="selectTable.stateStr" :disabled="true"></el-input>
      </el-form-item>
      <el-form-item label="审核结果" label-width="120px">
        <el-input v-model="selectTable.auditRemark" :disabled="true"></el-input>
      </el-form-item>
      <el-form-item label="店铺名称" label-width="120px">
        <el-input v-model="selectTable.name" auto-complete="off"></el-input>
      </el-form-item>
      <el-form-item label="未结算交易额(元)" label-width="120px">
        <el-input v-model="selectTable.unliquidatedAmount" :disabled="true"></el-input>
      </el-form-item>
      <el-form-item label="已结算交易额（元)" label-width="120px">
        <el-input v-model="selectTable.totalAmount" :disabled="true"></el-input>
      </el-form-item>
      <el-form-item label="平台收取费率(%)" label-width="120px">
        <el-input v-model="selectTable.platform_rate" type="number"></el-input>
      </el-form-item>

      <el-form-item label="详细地址" label-width="120px">
        <el-autocomplete
          v-model="address.address"
          :fetch-suggestions="querySearchAsync"
          placeholder="请输入地址"
          style="width: 100%"
          @select="addressSelect"
        ></el-autocomplete>
        <span>当前城市：{{ city.name }}</span>
      </el-form-item>
      <el-form-item label="店铺介绍" label-width="120px">
        <el-input v-model="selectTable.description"></el-input>
      </el-form-item>
      <el-form-item label="联系电话" label-width="120px">
        <el-input v-model="selectTable.phone"></el-input>
      </el-form-item>
      <el-form-item label="店铺分类" label-width="120px">
        <el-cascader
          :options="categoryOptions"
          v-model="selectedCategory"
          change-on-select
        ></el-cascader>
      </el-form-item>
      <el-form-item label="商铺图片" label-width="100px">
        <el-upload
          class="avatar-uploader"
          :action="fileMgrUrl"
          :headers="uploadHeaders"
          :show-file-list="false"
          :on-success="handleServiceAvatarScucess"
          :before-upload="beforeAvatarUpload"
        >
          <img v-if="selectTable.image_path" :src="selectTable.image" class="avatar" />
          <i v-else class="el-icon-plus avatar-uploader-icon"></i>
        </el-upload>
      </el-form-item>
    </el-form>
  </div>
</template>

<script>
import { getApiUrl } from '@/utils/utils';
import { getToken } from '@/utils/auth';
import { cityGuess } from '@/api/getData';
import permission from '@/directive/permission/index.js';
import {
  getResturants,
  getResturantsCount,
  foodCategory,
  updateResturant,
  searchplace,
} from '@/api/business/shop';

export default {
  directives: { permission },
  data() {
    return {
      city: {},
      count: 0,
      fileMgrUrl: getApiUrl() + '/file',
      uploadHeaders: {
        Authorization: '',
      },
      tableData: [],
      currentPage: 1,
      selectTable: {},
      dialogFormVisible: false,
      categoryOptions: [],
      selectedCategory: [],
      address: {},
      total: 0,
      stateList: [
        { label: '审核中', value: '0' },
        { label: '审核通过', value: '1' },
        { label: '审核拒绝', value: '-1' },
      ],
      audit: { show: false, auditRemark: '' },
      listQuery: {
        page: 1,
        limit: 20,
        name: undefined,
        state: '',
      },
    };
  },
  created() {
    this.initData();
    this.uploadHeaders['Authorization'] = getToken();
  },

  methods: {
    async initData() {
      try {
        cityGuess().then((response) => {
          this.city = response.data;
          getResturantsCount().then((response2) => {
            this.count = response2.count;
            this.fetchData();
          });
        });
      } catch (err) {
        console.log('获取数据失败', err);
      }
    },
    async getCategory() {
      try {
        const response = await foodCategory();
        const categories = response.data;
        categories.forEach((item) => {
          if (item.sub_categories.length) {
            const addnew = {
              value: item.name,
              label: item.name,
              children: [],
            };
            item.sub_categories.forEach((subitem, index) => {
              if (index === 0) {
                return;
              }
              addnew.children.push({
                value: subitem.name,
                label: subitem.name,
              });
            });
            this.categoryOptions.push(addnew);
          }
        });
      } catch (err) {
        console.log('获取商铺种类失败', err);
      }
    },
    async fetchData() {
      getResturants(this.listQuery).then((response) => {
        const restaurants = response.data.records;
        this.total = response.data.total;
        this.tableData = [];
        restaurants.forEach((item) => {
          const tableData = {};
          tableData.name = item.name;
          tableData.address = item.address;
          tableData.description = item.description;
          tableData.id = item.id;
          tableData.phone = item.phone;
          tableData.rating = item.rating;
          tableData.recent_order_num = item.recent_order_num;
          tableData.category = item.category;
          tableData.image_path = item.image_path;
          tableData.state = item.state;
          tableData.stateStr = item.stateStr;
          tableData.auditRemark = item.auditRemark;
          tableData.disabled = item.disabled;
          tableData.unliquidatedAmount = item.unliquidatedAmount;
          tableData.totalAmount = item.totalAmount;
          tableData.platform_rate = item.platform_rate;
          this.selectTable = tableData;
          this.selectTable.image =
            getApiUrl() + '/file/getImgStream?fileName=' + tableData.image_path;
          this.address.address = tableData.address;

          this.selectedCategory = tableData.category.split('/');
          if (!this.categoryOptions.length) {
            this.getCategory();
          }
        });
      });
    },

    search() {
      this.fetchData();
    },
    addFood(row) {
      this.$router.push({ path: '/business/food/add', query: { restaurant_id: row.id } });
    },
    viewFood(row) {
      this.$router.push({ path: '/business/food', query: { restaurant_id: row.id } });
    },
    async querySearchAsync(queryString, cb) {
      if (queryString) {
        try {
          const cityList = await searchplace(this.city.id, queryString);
          if (cityList instanceof Array) {
            cityList.map((item) => {
              item.value = item.address;
              return item;
            });
            cb(cityList);
          }
        } catch (err) {
          console.log(err);
        }
      }
    },
    addressSelect(vale) {
      const { address, latitude, longitude } = vale;
      this.address = { address, latitude, longitude };
    },
    handleServiceAvatarScucess(res) {
      this.selectTable.image_path = res.data.realFileName;
      this.selectTable.image = getApiUrl() + '/file/getImgStream?fileName=' + res.data.realFileName;
    },
    beforeAvatarUpload(file) {
      const isRightType = file.type === 'image/jpeg' || file.type === 'image/png';
      const isLt2M = file.size / 1024 / 1024 < 2;

      if (!isRightType) {
        this.$message.error('上传头像图片只能是 JPG 格式!');
      }
      if (!isLt2M) {
        this.$message.error('上传头像图片大小不能超过 2MB!');
      }
      return isRightType && isLt2M;
    },
    async updateShop() {
      try {
        Object.assign(this.selectTable, this.address);
        this.selectTable.category = this.selectedCategory.join('/');
        updateResturant(this.selectTable).then(() => {
          this.$message({
            type: 'success',
            message: '更新店铺信息成功',
          });
          this.getResturants();
        });
      } catch (err) {
        console.log('更新餐馆信息失败', err);
        this.$message({
          type: 'error',
          message: err,
        });
      }
    },
  },
};
</script>

<style lang="scss">
.demo-table-expand {
  font-size: 0;
}

.demo-table-expand label {
  width: 90px;
  color: #99a9bf;
}

.demo-table-expand .el-form-item {
  margin-right: 0;
  margin-bottom: 0;
  width: 50%;
}

.table_container {
  padding: 20px;
}

.Pagination {
  display: flex;
  justify-content: flex-start;
  margin-top: 8px;
}

.avatar-uploader .el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}

.avatar-uploader .el-upload:hover {
  border-color: #20a0ff;
}

.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 120px;
  height: 120px;
  line-height: 120px;
  text-align: center;
}

.avatar {
  width: 120px;
  height: 120px;
  display: block;
}
</style>
